<!--
 * @Author: Rain
 * @Date: 2023/10/08 16:48:11
 * @LastEditTime: 2023/11/17 20:44:47
 * @Description: Do Something
-->
<template>
  <div class="app-container w-full h-full overflow-hidden">
    <div class="head-container w-full h-full overflow-hidden flex flex-col">
      <div class="flex items-center justify-end search pb-10">
        <label class="el-form-item-label">班级名称:</label>
        <el-input
          v-model="query.name"
          clearable
          placeholder="班级名称"
          style="width: 185px"
          class="filter-item"
          @keyup.enter.native="crud.toQuery"
        />
        <label class="el-form-item-label">课程:</label>
        <el-select v-model="query.courseNo" placeholder="请选择" clearable filterable>
          <el-option
            v-for="item in courseList"
            :key="item.courseNo"
            :label="item.courseName"
            :value="item.courseNo"
          />
        </el-select>
        <rrOperation :crud="crud" />
        <crudOperation :permission="permission" />
      </div>
      <div class="w-full flex-1 overflow-hidden">
        <el-table
          ref="table"
          v-loading="crud.loading"
          :data="crud.data"
          size="small"
          style="width: 100%"
          height="100%"
          @selection-change="crud.selectionChangeHandler"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="name" label="班级名称" />
          <el-table-column prop="courseNo" label="课程">
            <template slot-scope="{ row }">
              {{ row.courseNo | getCourse(courseList) }}
            </template>
          </el-table-column>
          <el-table-column prop="meals" label="餐费" />
          <el-table-column prop="seatingMapImage" label="座位图">
            <template slot-scope="{ row }">
              <img
                :src="row.seatingMapImage | imgTransform"
                alt=""
                style="width: 40px; height: 40px"
              >
            </template>
          </el-table-column>
          <el-table-column prop="auditClock" label="是否需要审核打卡">
            <template slot-scope="{ row }">
              {{ row.auditClock ? "是" : "否" }}
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态">
            <template slot-scope="{ row }">
              {{ row.status ? "启用" : "禁用" }}
            </template>
          </el-table-column>
          <el-table-column
            v-if="checkPer(['admin', 'courseClass:edit', 'courseClass:del'])"
            label="操作"
            width="210px"
            align="center"
          >
            <template slot-scope="scope">
              <div class="flex items-center">
                <el-button
                  type="primary"
                  size="mini"
                  class="mr-2"
                  icon="el-icon-user"
                  @click="bindUser(scope.row)"
                >学员管理</el-button>
                <udOperation :data="scope.row" :permission="permission" />
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <pagination />
    </div>
    <el-dialog
      :close-on-click-modal="false"
      :before-close="crud.cancelCU"
      :visible.sync="crud.status.cu > 0"
      :title="crud.status.title"
      width="500px"
    >
      <el-form ref="form" :model="form" :rules="rules" size="small" label-width="80px">
        <el-form-item
          label="班级名称"
          prop="name"
          :rules="{ required: true, message: '请输入班级名称', trigger: 'blur' }"
        >
          <el-input
            v-model="form.name"
            style="width: 370px"
            placeholder="请输入班级名称"
          />
        </el-form-item>
        <el-form-item
          label="课程"
          prop="courseNo"
          :rules="{
            required: true,
            message: '请选择课程',
            trigger: ['blur', 'change'],
          }"
        >
          <el-select
            v-model="form.courseNo"
            placeholder="请选择"
            clearable
            filterable
            style="width: 370px"
          >
            <el-option
              v-for="item in courseList"
              :key="item.courseNo"
              :label="item.courseName"
              :value="item.courseNo"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          label="餐费"
          prop="meals"
          :rules="{ required: true, message: '请输入餐费', trigger: 'blur' }"
        >
          <el-input
            v-model.number="form.meals"
            style="width: 370px"
            placeholder="请输入餐费"
          />
        </el-form-item>
        <el-form-item label="是否需要审核打卡">
          <el-radio-group v-model="form.auditClock">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="form.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          label="座位图"
          prop="seatingMapImage"
          :rules="{ required: true, message: '请上传座位图', trigger: 'blur' }"
        >
          <uploadImage
            ref="uploadImage"
            :src="form.seatingMapImage"
            @upload="uploadAction"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="default" @click="crud.cancelCU">取消</el-button>
        <el-button
          :loading="crud.status.cu === 2"
          type="primary"
          @click="doSubmitAction"
        >确认</el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="visible" title="学员管理" :close-on-click-modal="false">
      <div class="w-full mb-3 flex items-center">
        <el-input
          v-model="userName"
          placeholder="学员姓名/手机号"
          clearable
          class="mr-20"
          @input="changeUserName"
        />
        <el-checkbox v-model="showSelect" label="已绑定学员" />
      </div>
      <div class="flex items-center flex-col" style="height: 500px">
        <div class="flex-1 overflow-hidden" style="width: 100%">
          <el-table
            ref="userTable"
            :data="showSelect ? bindRow.studentList : userList"
            class="userTable"
            height="100%"
            row-key="openId"
            @select="handleSelect"
            @select-all="handleSelectAll"
          >
            <el-table-column type="selection" />
            <el-table-column property="userName" label="姓名" align="center" />
            <el-table-column property="nickname" label="昵称" align="center" />
            <el-table-column property="mobile" label="手机号" align="center" />
            <el-table-column property="groupNumber" label="组号" align="center">
              <template slot-scope="{ row }">
                <el-input v-model="row.groupNumber" placeholder="输入组号" />
              </template>
            </el-table-column>
            <el-table-column property="payMeals" label="餐费" align="center">
              <template slot-scope="{ row }">
                <el-select v-model="row.mealsStatus" placeholder="请选择">
                  <el-option
                    v-for="item in options"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <el-pagination
          style="margin-top: 10px"
          background
          layout="prev, pager, next"
          :total="userQuery.total"
          :current-page.sync="userQuery.page"
          @current-change="changePage"
        />
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="default" @click="doAction(0)">取消</el-button>
        <el-button type="primary" @click="doAction(1)">确认</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import crudCourseClass, { bindStudent, getStudent } from '@/api/courseClass'
import { initData } from '@/api/data'
import CRUD, { presenter, header, form, crud } from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import crudOperation from '@crud/CRUD.operation'
import udOperation from '@crud/UD.operation'
import pagination from '@crud/Pagination'
import uploadImage from '@/components/uploadImage'
import { debounce } from 'lodash'
const defaultForm = {
  classId: null,
  classNo: null,
  name: null,
  status: 1,
  createTime: null,
  createby: null,
  updateTime: null,
  updateby: null,
  seatingMapImage: null,
  courseNo: null,
  meals: null,
  auditClock: 1
}
export default {
  name: 'CourseClass',
  filters: {
    getCourse(value, list) {
      const course = list.find((item) => {
        return item.courseNo === value
      })
      return course && course.courseName
    }
  },
  components: { pagination, crudOperation, rrOperation, udOperation, uploadImage },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  cruds() {
    return CRUD({
      title: '课程班级',
      url: 'api/courseClass',
      idField: 'classId',
      sort: 'classId,desc',
      crudMethod: { ...crudCourseClass }
    })
  },
  data() {
    return {
      permission: {
        add: ['admin', 'courseClass:add'],
        edit: ['admin', 'courseClass:edit'],
        del: ['admin', 'courseClass:del']
      },
      rules: {},
      queryTypeOptions: [
        { key: 'name', display_name: '班级名称' },
        { key: 'courseNo', display_name: '课程编号' }
      ],
      courseList: [],
      userList: [],
      visible: false,
      userName: '',
      bindRow: { studentList: [] },
      userQuery: {
        total: 0,
        page: 0,
        size: 10
      },
      options: [
        { label: '已付', value: true },
        { label: '未付', value: false }
      ],
      showSelect: false
    }
  },
  watch: {
    showSelect(val) {
      if (val) {
        this.bindRow.studentList.map((item) => {
          const row = this.userList.find((u) => u.openId === item.openId)
          const { mealsStatus, groupNumber } = item
          Object.assign(row, { mealsStatus: !!mealsStatus, groupNumber })
          this.$refs['userTable'].toggleRowSelection(row, true)
        })
      }
    }
  },
  mounted() {
    initData('api/courseInfo').then((res) => {
      const { content } = res
      this.courseList = content
    })
    this.queryWxUser()
  },
  methods: {
    // 钩子：在获取表格数据之前执行，false 则代表不获取数据
    [CRUD.HOOK.beforeRefresh]() {
      return true
    },
    uploadAction(e) {
      this.form.seatingMapImage = e
    },
    queryWxUser() {
      initData('api/wxUser', {
        size: this.userQuery.size,
        page: this.userQuery.page,
        realName: this.userName,
        sort: 'id,desc'
      }).then((res) => {
        const { content, totalElements } = res
        this.userQuery.total = totalElements
        this.userList = content.map((item) => {
          const { realName, mobile, nickname, openId } = item
          return {
            userName: realName,
            mobile,
            groupNumber: '',
            mealsStatus: false,
            nickname,
            openId
          }
        })
      })
    },
    bindUser(row) {
      this.visible = !this.visible
      this.bindRow = row
      const { classNo } = row
      getStudent({ classNo }).then((res) => {
        const { content } = res
        this.bindRow['studentList'] = content
        content.map((item) => {
          const row = this.userList.find((u) => u.openId === item.openId)
          const { mealsStatus, groupNumber } = item
          Object.assign(row, { mealsStatus: !!mealsStatus, groupNumber })
          this.$refs['userTable'].toggleRowSelection(row, true)
        })
      })
    },
    changePage(e) {
      this.userQuery.page = e
      this.queryWxUser()
    },
    changeUserName: debounce(function(e) {
      this.userName = e
      this.userQuery.page = 0
      this.queryWxUser()
    }, 500),
    handleSelect(e, row) {
      const flag = e.some((item) => item.openId === row.openId)
      if (flag) {
        this.bindRow['studentList'].push(row)
      } else {
        const index = this.bindRow['studentList'].findIndex(
          (item) => item.openId === row.openId
        )
        if (index > -1) this.bindRow['studentList'].splice(index, 1)
      }
    },
    doAction(flag) {
      if (flag === 0) {
        this.bindRow = {}
        this.userName = ''
        this.$refs['userTable'].clearSelection()
        this.visible = false
      } else {
        const { classNo, courseNo, studentList } = this.bindRow
        if (studentList.length === 0) {
          this.$message({
            type: 'error',
            message: '请选择学生'
          })
          return
        } else {
          const flag = studentList.some((item) => item.groupNumber.trim() === '')
          if (flag) {
            this.$message({
              type: 'error',
              message: '请完善组号'
            })
            return
          }
        }
        bindStudent({ classNo, courseNo, studentList })
          .then(() => {
            this.$message({
              type: 'success',
              message: '操作成功!'
            })
            this.visible = false
            this.$refs['userTable'].clearSelection()
            this.userQuery.page = 0
            this.userName = ''
            this.queryWxUser()
          })
          .catch(() => {
            this.$message({
              type: 'error',
              message: '操作失败!'
            })
          })
      }
    },
    handleSelectAll() {
      this.$refs['userTable'].clearSelection()
    },
    doSubmitAction() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          this.$refs['uploadImage'].handleUpload().then((res) => {
            this.crud.submitCU()
          })
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep {
  .userTable {
    thead {
      .el-table-column--selection {
        .el-checkbox {
          display: none;
        }
      }
    }
  }
}
</style>
